package com.aispeech.task.common.config;

import com.aispeech.task.common.data.domain.Task;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StreamOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@SuppressWarnings("unchecked")
@Configuration
public class RedisConfig {
    public final static String STREAM_NAME = "stream:task";
    public final static String STREAM_GROUP = "stream:group:task";
    public static final String HASH_TASK_KEY = "hash:tasks";

    @Autowired
    ObjectMapper objectMapper;

    @Bean
    public RedisTemplate<String, Task> redisTaskTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Task> template = new RedisTemplate<>();

        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Task.class);

        jacksonSeial.setObjectMapper(objectMapper);
        template.setValueSerializer(jacksonSeial);
        template.setKeySerializer(new StringRedisSerializer());

        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    @Bean
    public HashOperations<String, String, Task> hashTaskOperations(RedisTemplate<String, Task> redisTaskTemplate) {
        return redisTaskTemplate.opsForHash();
    }

    @Bean
    public StreamOperations<String, String, String> stringStreamOperations(RedisTemplate<String, String> redisTemplate) {
        return redisTemplate.opsForStream();
    }
}
